package com.luoran.car.controller;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.luoran.car.config.CustomCaptchaGenerator;
import com.luoran.car.config.EmailService;
import com.luoran.car.domain.SysCarCustomer;
import com.luoran.car.domain.customer.RegisterCustomer;
import com.luoran.car.service.SysCarCustomerService;
import com.luoran.car.util.Result;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "客户控制类")
@CrossOrigin(origins = "http://localhost:8080", allowCredentials = "true")
@RestController
@RequestMapping("customer")
public class CustomerController {


    @Autowired
    MinioClient minioClient;

    @Value(value = "${minio.bucket-name}")
    private String bucket;

    @Value(value = "${minio.url}")
    private String url;

    @Autowired
    HttpServletRequest request;

    @Autowired
    SysCarCustomerService carCustomerService;


    @Autowired
    EmailService emailService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("login")
    @ApiOperation("登录接口")
    public Result login(@RequestBody SysCarCustomer carCustomer) {

       SysCarCustomer sysCarCustomer =  carCustomerService.selectLoginCustomer(carCustomer.getCustomerName());

        System.out.println(sysCarCustomer.toString());
        if (carCustomer == null) {
            return Result.fail("账号或密码错误");
        }

        if (!carCustomer.getLoginPassword().equals(sysCarCustomer.getLoginPassword())) {
            return Result.fail("账号或密码错误");
        }
        String code = (String) redisTemplate.opsForValue().get("code");
        if (!code.equals(carCustomer.getCode())) {
            return Result.fail("验证码错误");
        }
        if (sysCarCustomer.getCustomerStatus()==1) {
            return Result.fail("账户已被锁定");
        }

        String token = JWT.create()
                .setPayload("customer", sysCarCustomer)
                .setSigner(JWTSignerUtil.none())
                .sign();
        return Result.success(token);
    }

    @GetMapping("newPassword")
    public Result newPassword(String email,String code, String newPassword) {

        SysCarCustomer sysCarCustomer = carCustomerService.selectSendEmail(email);
        System.out.println(sysCarCustomer.toString()+"aaaaaaaaaaaaaaaaaaaaaaaaa");
        String redisCode = (String) redisTemplate.opsForValue().get("newPassword" + sysCarCustomer.getEmail());

        if (!code.equals(redisCode)) {
            return Result.fail("验证码错误");
        }
        sysCarCustomer.setLoginPassword(newPassword);
       Boolean bool  =  carCustomerService.updataPassword(sysCarCustomer);
       return bool?Result.success("修改成功"):Result.fail("修改失败");
    }

    @GetMapping("sendEmail")
    public Result sendEmail(String email) throws MessagingException {

       SysCarCustomer sysCarCustomer =  carCustomerService.selectSendEmail(email);

        if (sysCarCustomer == null) {
            return Result.fail("邮箱不存在");
        }

        String code = RandomUtil.randomString(5);
        redisTemplate.opsForValue().set("newPassword"+email,code);

        emailService.sendEmailWithAttachment(email,"重置密码",code);
        return Result.success("发送成功");
    }

    @PostMapping("registerCustomer")
    public Result registerCustomer(@RequestBody RegisterCustomer registerCustomer) {

       Boolean bool =  carCustomerService.register(registerCustomer);
       return bool?Result.success():Result.fail("系统异常");
    }




    @GetMapping("lockAccount")
    public Result lockAccount(Integer id) {
        Boolean bool = carCustomerService.lockAccount(id);
        return bool?Result.success("锁定成功"):Result.fail("系统异常");
    }

    @GetMapping("unitAccount")
    public Result unitAccount(Integer id) {
        Boolean bool = carCustomerService.unitAccount(id);
        return bool?Result.success("解锁成功"):Result.fail("系统异常");
    }

    @PostMapping("customerUpload")
    public Result customerUpload(MultipartFile file) {

      String fileName =   UUID.randomUUID()+"_"+file.getOriginalFilename();
        try {
            minioClient.putObject(PutObjectArgs.builder()
                            .object(fileName)
                            .bucket(bucket)
                            .stream(file.getInputStream(), file.getSize(), -1)
                            .contentType(file.getContentType())
                    .build());
            return Result.success(url+"/"+bucket+"/"+fileName);

        } catch (Exception a) {
            a.printStackTrace();
            return Result.fail();
        }
    }

    @GetMapping("CustomerGenerator")
    public Result CustomerGenerator(String uid) {
        String imageCode = CustomCaptchaGenerator.generateCaptcha();
        String code = CustomCaptchaGenerator.getGeneratedCaptchaText();
        redisTemplate.opsForValue().set("code",code);
        redisTemplate.opsForValue().set(uid,CustomCaptchaGenerator.getGeneratedCaptchaText(),2, TimeUnit.MINUTES);
        return Result.success(imageCode);
    }


    @GetMapping("CustomerList")
    public Result customerList() {
        List<SysCarCustomer> list =  carCustomerService.customerList();
        return Result.success(list);
    }


    @GetMapping("CustomerDel")
    public Result customerDel(Integer id) {
        Boolean del = carCustomerService.customerDel(id);
        return Result.success(del);
    }

    @PostMapping("CustomerUpdata")
    public Result customerUpdata(@RequestBody SysCarCustomer carCustomer) {
        Boolean updata = carCustomerService.customerUpdata(carCustomer);
        return Result.success(updata);
    }

    @PostMapping("CustomerInsert")
    public Result customerInsert(@RequestBody SysCarCustomer carCustomer) {
        Boolean insert = carCustomerService.customerInsert(carCustomer);
        return Result.success(insert);
    }

}
